import Vuex from 'vuex'
import Vue from 'vue'
Vue.use(Vuex)

export const store = new Vuex.Store({
    state: {
        isLogin: false,
        user: {},
        userId: '',
        address_id: ''
    },
    getters: {
        get_address(state) {
            return state.address_id
        },
        get_user(state) {
            return state.user
        }
    },
    mutations: {
        login(state, user) {
            // 用户已登录
            state.isLogin = true

            state.user = user
            // 存储会员 member 数据
            uni.setStorage({
                key: '__user',
                data: state.user
            })

            state.userId = user.user_id
            uni.setStorage({
                key: '__user_id',
                data: state.userId
            })
        },
        // 注销
        logout(state) {
            state.isLogin = false

            state.user = {}
            uni.removeStorage({
                key: '__user'
            })

            state.userId = ''
            uni.removeStorage({
                key: '__user_id'
            })
        },
        setUserId(state, userId) {
            state.userId = userId
            uni.setStorage({
                key: '__user_id',
                data: state.userId
            })
        },
        set_address(state, val) {
            state.address_id = val
        },
        set_user(state, val) {
            state.user = val
        }
    },
    actions: {
        set_address({
            commit
        }, val) {
            commit('set_address', val)
        },
        set_user({
            commit
        }, val) {
            commit('set_user', val)
        },
        setDisplaceStatus({
            commit
        }) {
            Vue.prototype.$http('get|api/User/index').then((res) => {
                // console.log('setDisplaceStatus', res)
                if (res.status === 1) {
                    const value = res.result.isChange || 0
                    commit('set_displaceStatus', value)
                }
            })
        }
    }
})
